/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-05-30 04:51:15
 * @modify date 2017-05-30 04:51:15
 * @desc [description]
*/

const IndexController = {}
const User = require('../models/User');
const Conf = require('../config/config')
const Tools = require('../libs/tools')
const jwt = require('jsonwebtoken')
IndexController.index = async (ctx, next) => {
  let username = 'Mankong'
  let password = 'abc@123'
  let displayName = '思微'
  let user = await User.findOne({ username, password }).exec()
  if (!user) {
    user = await User.create({ username, password, displayName })
  }
  return ctx.body = user.avatar
}
IndexController.test = async (ctx, next) => {
  let username = ctx.request.body.username
  let password = ctx.request.body.password
  let user = await User.findOne({ username, password }).exec()
  
  // return ctx.body = Tools.trimObjectValue(ctx.request.body)
  ctx.body = ctx.authuser

  // if (user) {
  //   delete user['password']
  //   let token = jwt.sign({
  //     exp: Math.floor(Date.now() / 1000) + (60 * 60),
  //     data: user
  //   }, Conf.jwtSecret)
  //   return ctx.body = {
  //     token: token,
  //     user: user
  //   }
  // } else {
  //   return ctx.body = {
  //     status: ctx.response.status,
  //     message: ctx.response.message,
  //     data: {info: '用户不存在'},
  //   }
  // }
}
IndexController.verify = async (ctx, next) => {

}
IndexController.login= async (ctx, next) => {
  let username = ctx.request.body.username
  let password = ctx.request.body.password
  let user = await User.findOne({username, password})
  if (user) {
    user = user.toObject( { getters: true, virtuals: true } )
    delete user.password
    const token = Tools.encrypted( jwt.sign( { data: user }, Conf.jwtSecret, { expiresIn: '24h' }))
    ctx.body = {
      token: token,
      user: user
    }
  } else {
    ctx.body = password
  }
}
IndexController.crypto = async (ctx, next) => {
  let users = await User.find({})
  if (users) {
    ctx.body = users
  } else {
    ctx.body = 'error'
  }
}
IndexController.users = async ( ctx, next ) => {
  let users = await User.find({})
  if (users) {
    ctx.body = {
      data: users,
      token: ctx.token,
      jwt_token: ctx.jwt_token,
      user: ctx.authuser
    }
  } else {
    ctx.body = 'error'
  }
}
module.exports = IndexController